package com.kehutong.house.app;

import com.kehutong.common.util.Token;
import com.kehutong.house.entity.Building;
import com.kehutong.house.entity.Community;
import com.kehutong.house.service.BuildService;
import com.kehutong.house.service.CommunityService;
import com.kehutong.house.service.HouseService;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.Objects;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 楼栋信息
 */
@MvcAction
@ReqMapping("/kht-bin/basic/building")
public class BuildingAction {

    @Inject
    private JdbcSession jdbcSession;
    @Inject
    private BuildService buildService;
    @Inject
    private HouseService houseService;
    @Inject
    private CommunityService communityService;

    /**
     * 小程序端使用
     * @param jsonObject
     * @return
     */
    @ReqMapping("/list")
    public Object getBuildings(JSONObject jsonObject) {
        String communityNo = jsonObject.getString("communityNo");
        if(Objects.isBlank(communityNo)){
            return Result.error(0, "小区编号不能为空");
        }
        Community community = Pool.get(Community.class, communityNo);
        if (Objects.isNull(community)) {
            return Result.error(0, "请选择小区管理中创建的小区");
        }
        List<Building> list = jdbcSession.findArray(Building.class)
                .eq(jsonObject, "communityNo")
                .like(jsonObject,"name")
                .eq("deleted", false)
                .order("name", "ASC").exe();

        return Result.success(list);
    }

    /**
     * 企微端使用
     * @param entity
     * @return
     * @throws Exception
     */
    @ReqMapping("/appGetSteward")
    public Object appGetSteward (Building entity) throws Exception {
        if(Objects.nonNull(entity)){
            JSONObject result = new JSONObject();
            result.put("id", entity.getId());
            result.put("name", entity.getName());
            result.put("unitName", entity.getUnitName());
            result.put("communityNo", entity.getCommunityNo());

            // 组装管家信息
            List<String> employeeNos = entity.getEmployeeNos();
            List<JSONObject> employees = new ArrayList<>();
            if(Objects.nonEmpty(employeeNos)){
                JSONArray array = communityService.getEmployees(employeeNos);
                array.forEach(item ->{
                    JSONObject temp = (JSONObject) item;

                    JSONObject employee = new JSONObject();
                    employee.put("avatar", temp.getString("avatar"));
                    employee.put("id", temp.getString("id"));
                    employee.put("name", temp.getString("name"));
                    employees.add(employee);
                });
            }
            result.put("employees", employees);


            Community community = Pool.get(Community.class, entity.getCommunityNo());
            // 组装所属部门信息
            String parentId = community.getParent_id();
            JSONObject department = new JSONObject();
            if(Objects.nonEmpty(parentId)){
                Map<String,JSONObject> departmentMap = communityService.getDepartmentMap(Arrays.asList(parentId));
                department.put("id", parentId);
                JSONObject temp = departmentMap.get(parentId);
                String name = "";
                if(Objects.nonEmpty(temp)){
                    name = temp.getString("name");
                }
                department.put("name", name);
            }
            result.put("department", department);

            return result;
        }else{
            return Result.error(0, "未获取到楼栋信息");
        }
    }

    /**
     * 企微端使用
     * @param jsonObject
     * @return
     */
    @ReqMapping("/appList")
    public Object appList(JSONObject jsonObject) {
        String communityNo = jsonObject.getString("communityNo");
        if(Objects.isBlank(communityNo)){
            return Result.error(0, "小区编号不能为空");
        }
        Community community = Pool.get(Community.class, communityNo);
        if (Objects.isNull(community)) {
            return Result.error(0, "请选择小区管理中创建的小区");
        }
        return Result.success(buildService.permissionQuery(jsonObject));
    }

    /**
     * 设置 管家
     * @param jsonObject
     * @return
     */
    @ReqMapping("/setting")
    public Object setting(JSONObject jsonObject){

        String id = jsonObject.getString("id");
        if(Objects.isEmpty(id)){
            return Result.error(0, "楼栋编号不能为空");
        }

        Building entity = Pool.get(Building.class, id);
        if(Objects.isNull(entity)){
            return Result.error(0, "占未查询到楼栋信息");
        }

        JSONArray employeeNos = jsonObject.getJSONArray("employeeIds");
        entity.setEmployeeNos(null);
        if(Objects.nonEmpty(employeeNos)){
            List<String> employees = JSONObject.parseArray(employeeNos.toString(),String.class);
            entity.setEmployeeNos(employees);
        }

        jdbcSession.updateById(entity);

        return Result.success();
    }

    @Bean(copy=true, isIgnoreNull = false)
    @ReqMapping("/update")
    public Object update(Building building) throws Exception {
        return buildService.update(building);
    }

    @Bean(newInstance=true, copy=true)
    @ReqMapping("/save")
    public Object save(Token token, Building building) throws Exception {
        return buildService.save(token, building);
    }

    @ReqMapping("/delete")
    public Object delete(Building item) {
        return buildService.delete(item);
    }

    @ReqMapping("/get")
    public Object get(Building entity) throws Exception {
        List<String> employeeNos = entity.getEmployeeNos();

        if(Objects.nonEmpty(employeeNos)){
            List<String> employeeNames = new ArrayList<>();
            JSONArray array = communityService.getEmployees(employeeNos);
            array.forEach(item ->{
                JSONObject temp = (JSONObject) item;
                employeeNames.add(temp.getString("name"));
            });
            entity.setEmployeeNames(employeeNames);
        }

        return entity;
    }
}
